#include <vector>
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
#include <stdlib.h>

#include "../include/cardprovider.h"
#include "../include/card.h"

using namespace std;

namespace mtga {

	CardProvider::CardProvider() {
		cards = new vector<Card*>();
	}

	CardProvider::~CardProvider() {
		for (vector<Card*>::iterator iterator = cards->begin(); iterator != cards->end(); ++iterator) {
			Card* card = *iterator;
			delete card;
		}
	}

	Card* CardProvider::findByName(string name) {
		for (vector<Card*>::iterator iterator = cards->begin(); iterator != cards->end(); ++iterator) {
			Card* card = *iterator;
			if (name == card->getName()) {
				return card;
			}
		}
		cout << "No se encuentra la carta '" << name << "' en la base de datos " << endl;
		return 0;
	}

	void CardProvider::loadCards() {
		std::cout << "Loading cards" << std::endl;
		std::ifstream inputStream;
		inputStream.open("resources/cards.txt");
		std::string line;
		std::vector<std::string> elements;
		int count = 0;
		while (std::getline(inputStream, line)) {
			std::istringstream mainString(line);
			std::string element;
			while (std::getline(mainString, element, '|')) {
				elements.push_back(element);
			}
			string name = elements[0];
			string cmcString = elements[2];
			// TODO hacer trim de los elementos en condiciones
			string::size_type pos = name.find_last_not_of(' ');
			if (pos != string::npos) {
				name.erase(pos + 1);
			}
			int cmc;
			std::istringstream ss(elements[1]);
			ss >> cmc;
			cards->push_back(new Card(name, cmc, cmcString));
			count++;
			elements.clear();
		}
		std::cout << "Readed " << count << " cards" << std::endl;
	}

}
